package com.yinda.dt.produce.module.order;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.ViewTreeObserver;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yinda.dt.produce.R;
import com.yinda.dt.produce.app.DemoActivity;
import com.yinda.dt.produce.app.DemoConfig;
import com.yinda.dt.produce.utils.ApplicationUtil;
import com.yinda.dt.produce.utils.DesUtil;
import com.yinda.dt.produce.utils.StatusBarUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import io.dcloud.EntryProxy;
import io.dcloud.common.DHInterface.ICore;
import io.dcloud.common.DHInterface.ISysEventListener;
import io.dcloud.common.DHInterface.IWebview;
import io.dcloud.common.DHInterface.IWebviewStateListener;
import io.dcloud.feature.internal.sdk.SDK;

public class OtherDetailActivity extends DemoActivity implements View.OnClickListener {

    private EntryProxy entryProxy;
    private WebViewListener webViewListener;

    private FrameLayout fl_content;

    private String url;

    private LinearLayout ll_left;
    private TextView tv_title;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_detail);

        ll_left = (LinearLayout) findViewById(R.id.ll_left);
        ll_left.setOnClickListener(this);
        tv_title = (TextView) findViewById(R.id.tv_title);

        int type = getIntent().getIntExtra("type", 0);
        if (type == 0) {
            return;
        }
        if (type == 1) {

            tv_title.setText("项目需求");

            try {

                JSONObject jsonParams = new JSONObject();
                jsonParams.put("key", DemoConfig.getInstance(this).getKey());
                jsonParams.put("phoneModel", Build.BRAND + "-" + Build.MODEL + "-" + Build.VERSION.RELEASE);
                jsonParams.put("appVersion", ApplicationUtil.getThisAPPVersionName(this));
                jsonParams.put("phoneType", "android");

                url = getString(R.string.defaultURL) + "/phone1_0!newOrder.action?" + "request=" + URLEncoder.encode(new DesUtil("dtsbsbdsb", true).encode(URLEncoder.encode(jsonParams.toString(), "utf-8")), "utf-8");

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (type == 2) {
            tv_title.setText("新建改造");

            try {

                JSONObject jsonParams = new JSONObject();
                jsonParams.put("key", DemoConfig.getInstance(this).getKey());
                jsonParams.put("phoneModel", Build.BRAND + "-" + Build.MODEL + "-" + Build.VERSION.RELEASE);
                jsonParams.put("appVersion", ApplicationUtil.getThisAPPVersionName(this));
                jsonParams.put("phoneType", "android");
                jsonParams.put("type", "1");

                url = getString(R.string.defaultURL) + "/phone1_0!newConstruction.action?" + "request=" + URLEncoder.encode(new DesUtil("dtsbsbdsb", true).encode(URLEncoder.encode(jsonParams.toString(), "utf-8")), "utf-8");

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (type == 3) {

            tv_title.setText("新建零星");

            try {

                JSONObject jsonParams = new JSONObject();
                jsonParams.put("key", DemoConfig.getInstance(this).getKey());
                jsonParams.put("phoneModel", Build.BRAND + "-" + Build.MODEL + "-" + Build.VERSION.RELEASE);
                jsonParams.put("appVersion", ApplicationUtil.getThisAPPVersionName(this));
                jsonParams.put("phoneType", "android");
                jsonParams.put("type", "2");

                url = getString(R.string.defaultURL) + "/phone1_0!newConstruction.action?" + "request=" + URLEncoder.encode(new DesUtil("dtsbsbdsb", true).encode(URLEncoder.encode(jsonParams.toString(), "utf-8")), "utf-8");

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        fl_content = (FrameLayout) findViewById(R.id.fl_content);

        webViewListener = new WebViewListener();
        entryProxy = EntryProxy.init(this, webViewListener);
        entryProxy.onCreate(this, savedInstanceState, SDK.IntegratedMode.WEBVIEW, null);
        fl_content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                webViewListener.iWebview.onRootViewGlobalLayout(fl_content);
            }
        });

        StatusBarUtil.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorPrimary));
        loadingDialog.show();

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_left) {
            finish();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return entryProxy.onActivityExecute(this, ISysEventListener.SysEventType.onCreateOptionMenu, menu);
    }

    @Override
    public void onPause() {
        super.onPause();
        entryProxy.onPause(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        entryProxy.onResume(this);
    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getFlags() != 0x10600000) {// 非点击icon调用activity时才调用newintent事件
            entryProxy.onNewIntent(this, intent);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        entryProxy.onStop(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean _ret = entryProxy.onActivityExecute(this, ISysEventListener.SysEventType.onKeyDown, new Object[]{keyCode, event});
        return _ret ? _ret : super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        boolean _ret = entryProxy.onActivityExecute(this, ISysEventListener.SysEventType.onKeyUp, new Object[]{keyCode, event});
        return _ret ? _ret : super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        boolean _ret = entryProxy.onActivityExecute(this, ISysEventListener.SysEventType.onKeyLongPress, new Object[]{keyCode, event});
        return _ret ? _ret : super.onKeyLongPress(keyCode, event);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        try {
            int temp = this.getResources().getConfiguration().orientation;
            if (entryProxy != null) {
                entryProxy.onConfigurationChanged(this, temp);
            }
            super.onConfigurationChanged(newConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        entryProxy.onActivityExecute(this, ISysEventListener.SysEventType.onActivityResult, new Object[]{requestCode, resultCode, data});
    }

    private class WebViewListener implements ICore.ICoreStatusListener {

        IWebview iWebview;

        @Override
        public void onCoreReady(ICore iCore) {
            // 调用SDK的初始化接口，初始化5+ SDK
            SDK.initSDK(iCore);
            // 设置当前应用可使用的5+ API
            SDK.requestAllFeature();
        }

        // 5+内核初始化完成时触发
        // 开发者要在5+内核初始化完成才能调用SDK.startWebApp()等接口启动指定目录下的5+Webapp
        @Override
        public void onCoreInitEnd(ICore iCore) {
            //设置单页面集成的appid
            String appid = "test1";
            // 单页面集成时要加载页面的路径，可以是本地文件路径也可以是网络路径

            String url1 = "https://www.baidu.com/";

            Log.d("xiaocan", url);

            iWebview = SDK.createWebview(OtherDetailActivity.this, url, appid, new IWebviewStateListener() {
                @Override
                public Object onCallBack(int i, Object o) {
                    switch (i) {
                        case IWebviewStateListener.ON_WEBVIEW_READY:
                            // 准备完毕之后添加webview到显示父View中，设置排版不显示状态，避免显示webview时，html内容排版错乱问题
                            ((IWebview) o).obtainFrameView().obtainMainView().setVisibility(View.INVISIBLE);
                            SDK.attach(fl_content, ((IWebview) o));
                            break;
                        case IWebviewStateListener.ON_PAGE_FINISHED:
                            // 页面加载完毕，设置显示webview
                            iWebview.obtainFrameView().obtainMainView().setVisibility(View.VISIBLE);
                            loadingDialog.dismiss();
                            break;
                    }
                    return null;
                }
            });

            final WebView webviewInstance = iWebview.obtainWebview();
            // 监听返回键
            webviewInstance.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        if (webviewInstance.canGoBack()) {
                            webviewInstance.goBack();
                            return true;
                        } else {
                            finish();
                            return true;
                        }
                    }
                    return false;
                }
            });

        }

        // 5+内核关闭时触发
        @Override
        public boolean onCoreStop() {
            return false;
        }

    }
}
